#include "myStdio.h"

MYFILE* creatFileObj(int fd, int flag)
{
    MYFILE* ret = (MYFILE*)malloc(sizeof(MYFILE));
    if(ret == NULL)
        return NULL;
    ret->fileno = fd;
    ret->flag = flag;
    ret->refreshMed = LINEREFRESH;
    ret->buffSize = 0;
    memset(ret->outBuff, 0, sizeof(ret->outBuff));
    return ret;
}

MYFILE* myfopen(const char *path, const char *mode)
{
    int flag = 0, fd = -1;
    if(!strcmp(mode, "w"))
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(!strcmp(mode, "a"))
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else if(!strcmp(mode, "r"))
    {
        flag = O_WRONLY;
        fd = open(path, flag);

    }
    else 
    {
        //TODO
    }

    if(fd == -1)
        return NULL;

    return creatFileObj(fd, flag);
}

void myfclose(MYFILE* fp)
{
    if(fp->fileno < 0)
        return;
    myfflush(fp);
    close(fp->fileno);
    free(fp);
    fp = NULL;
}

void myfwrite(const void *ptr, size_t size, MYFILE *stream)
{
    memcpy(stream->outBuff + stream->buffSize, ptr, size);
    stream->buffSize += size;
    // 行刷新
    if(stream->refreshMed & LINEREFRESH && stream->outBuff[stream->buffSize - 1] == '\n')
    {
        myfflush(stream);
    }
}

void myfflush(MYFILE* stream)
{
    if(stream->buffSize <= 0)
        return;
    write(stream->fileno, stream->outBuff, stream->buffSize);//立即将数据从语言级缓冲区写入内核缓冲区
    stream->buffSize = 0;
    fsync(stream->fileno);//立即刷新内核缓冲区
}
